package com.flowersinc.shop.views
{
	import com.flowersinc.shop.events.HomeViewEvent;
	import com.flowersinc.shop.model.Flower;
	
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	import mx.containers.VBox;
	import mx.containers.ViewStack;
	
	import org.goverla.managers.ApplicationManager;

	public class MainViewBase extends VBox
	{
		public var homeView : HomeView;

		[Bindable]
		public var viewStack : ViewStack;
		
		[Bindable]
		public var selectedFlower : Flower;
		
		[Bindable]	
		public var flowers : ArrayCollection;
		
			
		protected function onInitialize() : void 
		{
			_urlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
			_urlLoader.load(_urlRequest);
		}
		
		protected function onChangeViewStack(event : Event) : void 
		{
			if (viewStack.selectedIndex == 0) {
				homeView.startShuffle();				
			}

			if (viewStack.selectedIndex == 1) {
				homeView.stopShuffle();
			}
		} 
			
		protected function onImageSelected(event : HomeViewEvent) : void 
		{
			viewStack.selectedIndex = 1;	
			selectedFlower = event.selectedFlower;
		}
		
		protected function onHomeImageClick() : void 
		{
			viewStack.selectedIndex = 0;
		}
		
		protected function onFlowerImageClick() : void 
		{
			viewStack.selectedIndex = 1;
		}
		
		protected function onHelpImageClick() : void 
		{
			viewStack.selectedIndex = 2;
		}
		
		private function onLoadComplete(evtObj:Event) : void 
		{ 
			_flowersXML = XML(_urlLoader.data); 
			addFlowers();
		}
		
		private function addFlowers() : void 
		{
			var result : ArrayCollection = new ArrayCollection();
			
			for each (var flower : XML in _flowersXML.flower) 
			{
				var flowerInstance : Flower = new Flower();
				
				flowerInstance.color = flower.@color;
				flowerInstance.name = flower.@type;
				flowerInstance.price = flower.@price;
				flowerInstance.amount = flower.@amount;
				flowerInstance.image = flower.@imageUrl;
				flowerInstance.thumbImage = flower.@thumbImageUrl;
				flowerInstance.rating = flower.@rating;
				flowerInstance.description = flower.description;
		
				result.addItem(flowerInstance);
			}
			
			flowers = result;
		}
			
		
		private var _flowersXML : XML = new XML();
		private var _urlRequest : URLRequest = 
			new URLRequest(ApplicationManager.instance.url + "data/flowers.xml"); 
		private var _urlLoader : URLLoader = new URLLoader();
	}
}